package com.wufun.overseas.main.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wufun.baselibrary.download.ScanApClientThread;
import com.wufun.baselibrary.utils.LogUtils;
import com.wufun.overseas.R;
import com.wufun.overseas.adapters.GameTransferHistoryAdapter;
import com.wufun.overseas.adapters.GameTransferListAdapter;
import com.wufun.overseas.main.base.MyActivity;
import com.wufun.overseas.main.base.MyApplication;
import com.wufun.overseas.main.service.SocketClientService;
import com.wufun.overseas.main.service.SocketServerService;
import com.wufun.overseas.models.bean.GameTransferBean;
import com.wufun.overseas.models.db.DownLoadModel;
import com.wufun.overseas.tools.DownloadManager;
import com.wufun.overseas.tools.MyDialog;
import com.wufun.overseas.tools.filetransfer.ApWifiConnectedReceiver;
import com.wufun.overseas.tools.filetransfer.ApWifiUtil;
import com.wufun.overseas.tools.filetransfer.DrawableDividerItemDecoration;
import com.wufun.overseas.tools.filetransfer.FileDeletRunable;
import com.wufun.overseas.tools.filetransfer.NetWorkConnectedReceiver;
import com.wufun.overseas.tools.filetransfer.PaPaLinearLayoutManager;
import com.wufun.overseas.tools.filetransfer.WifiUtils;
import com.wufun.overseas.tools.socket.SocketCommendManager;
import com.wufun.overseas.tools.socket.client.ClientService;
import com.wufun.overseas.tools.socket.entity.SocketConfig;
import com.wufun.overseas.tools.socket.server.SocketService;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by tangbl on 2017/12/5 0005.
 */
public class GameTransferActivity extends MyActivity {

    @Bind(R.id.game_transfer_back_img)
    ImageView gameTransferBackImg;
    @Bind(R.id.game_transfer_title_txt)
    TextView gameTransferTitleTxt;
    @Bind(R.id.game_transfer_bar_img)
    ImageView gameTransferBarImg;
    @Bind(R.id.game_transfer_left_phone_txt)
    TextView gameTransferLeftPhoneTxt;
    @Bind(R.id.game_transfer_right_phone_txt)
    TextView gameTransferRightPhoneTxt;
    @Bind(R.id.game_transfer_top_rl)
    RelativeLayout gameTransferTopRl;
    @Bind(R.id.game_transfer_bottom_navigation_left_txt)
    TextView left_nagivation_bar_txt;
    @Bind(R.id.game_transfer_bottom_navigation_right_txt)
    TextView right_nagivation_bar_txt;
    @Bind(R.id.game_transfer_bottom_navigation_bar_ll)
    LinearLayout gameTransferBottomNavigationBarLl;
    @Bind(R.id.game_transfer_selected_num_txt)
    TextView select_num_txt;
    @Bind(R.id.game_transfer_list_choose_all_txt)
    TextView select_all_txt;
    @Bind(R.id.game_transfer_history_list_hint_txt)
    TextView gameTransferHistoryListHintTxt;
    @Bind(R.id.game_transfer_list_hint_close_img)
    ImageView gameTransferListHintCloseImg;
    @Bind(R.id.game_transfer_history_hint_rl)
    RelativeLayout histroy_hint_rl;
    @Bind(R.id.game_transfer_list_rv)
    RecyclerView game_transfer_list;
    @Bind(R.id.game_transfer_historyList_rv)
    RecyclerView game_transfer_historyList;
    @Bind(R.id.game_transfer_bottom_rl)
    RelativeLayout gameTransferBottomRl;
    @Bind(R.id.game_transfer_ok_btn)
    Button tansfer_ok_btn;

    private final int LEFT_BAR = 1;
    private final int RIGHT_BAR = 2;

    private int Flag;
    private SocketCommendManager scManager;
    private File cacheRoot;
    private PowerManager powerManager;
    private PowerManager.WakeLock wakeLock = null;

    private Socket mSocket = null;
    //最后一次接收到Socket信息
    private long lastReceiverTime;
    private SocketService socketService;
    private ClientService client;

    private ExecutorService mExecutor = Executors.newCachedThreadPool();
    private SocketStatusRunable mRunable = null;
    private FileDeletRunable fileRunable = null;
    private Future mFuture = null;

    private ScanApClientThread apClientRunable = null;
    private Future apClientFuture = null;

    private ApWifiConnectedReceiver apWifiConnectedReceiver;
    private NetWorkConnectedReceiver netWorkConnectedReceiver;

    private boolean sending = false;//文件是否发送中
    private MyDialog mDialog = null;

    private GameTransferListAdapter gameListAdapter;
    private GameTransferHistoryAdapter histroyGameListAdapter;
    private SparseArray<GameTransferBean> game_array;//下载的游戏列表
    private SparseArray<GameTransferBean> accept_game_array;//待接收游戏列表
    private List<DownLoadModel> gameDownloadTasks;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game_transfer);
        ButterKnife.bind(this);
    }

    public static Intent buildIntent(Context context, int Flag) {
        Intent intent = new Intent(context, GameTransferActivity.class);
        intent.putExtra("Flag", Flag);
        return intent;
    }

    @Override
    public void initWidget(View... v) {
        super.initWidget(v);
        Flag = getIntent().getIntExtra("Flag", 0);

        powerManager = (PowerManager) getSystemService(POWER_SERVICE);

        scManager = SocketCommendManager.getInstance();
        cacheRoot = new File(MyApplication.getMyApplication().getAppRootPath());
        if (!cacheRoot.exists()) {
            cacheRoot.mkdirs();
        }
        wakeLock = powerManager.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK, "My Lock");
        wakeLock.acquire();
        bindService();

        initData();

        initRecyclerView();
        if (Flag == SocketConfig.SOCKET_SERVER_FLAG) {
            nagivationBarTextSelectedStatusChange(RIGHT_BAR);
            registApWifiStatus();
            listApClients();
        } else if (Flag == SocketConfig.SOCKET_CLIENT_FLAG) {
            nagivationBarTextSelectedStatusChange(LEFT_BAR);
            registWifiConnected();
            scManager.sendDeviceModel();
        }
    }

    private void initData() {
        gameDownloadTasks = DownloadManager.getInstance().getAllFinishDownload();
        game_array = new SparseArray<>();
        accept_game_array = new SparseArray<>();
    }

    //初始化RecyclerView
    private void initRecyclerView() {
        //游戏列表
        game_transfer_list.addItemDecoration(new DrawableDividerItemDecoration(getResources()
                .getDrawable(R.drawable.recyclerview_horizontal_divider), true, false));
        RecyclerView.ItemAnimator itemAnimator = game_transfer_list.getItemAnimator();
        itemAnimator.setChangeDuration(0);
        game_transfer_list.setHasFixedSize(true);
        game_transfer_list.setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER);//去除阴影
        PaPaLinearLayoutManager layoutManager = new PaPaLinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        game_transfer_list.setLayoutManager(layoutManager);
        gameListAdapter = new GameTransferListAdapter(mContext);
        gameListAdapter.setAdapterData(game_array);
        game_transfer_list.setAdapter(gameListAdapter);
        //传输记录
        game_transfer_historyList.addItemDecoration(new DrawableDividerItemDecoration(getResources()
                .getDrawable(R.drawable.recyclerview_horizontal_divider), true, false));
        RecyclerView.ItemAnimator historyItemAnimator = game_transfer_historyList.getItemAnimator();
        historyItemAnimator.setChangeDuration(0);//取消 改变item 时候的动画
        game_transfer_historyList.setHasFixedSize(true);
        game_transfer_historyList.setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER);//去除阴影
        PaPaLinearLayoutManager historyLayoutManager = new PaPaLinearLayoutManager(this);
        historyLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        game_transfer_historyList.setLayoutManager(historyLayoutManager);
        histroyGameListAdapter = new GameTransferHistoryAdapter(mContext);
        histroyGameListAdapter.setAdapterData(accept_game_array);
        game_transfer_historyList.setAdapter(histroyGameListAdapter);
    }

    //绑定服务
    private void bindService() {
        Intent intent = null;
        if (Flag == SocketConfig.SOCKET_SERVER_FLAG) {
            intent = new Intent(GameTransferActivity.this, SocketServerService.class);
        } else if (Flag == SocketConfig.SOCKET_CLIENT_FLAG) {
            intent = new Intent(GameTransferActivity.this, SocketClientService.class);
        }
        this.bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }

    //取消绑定
    private void stopService() {
        Intent intent = null;
        unbindService(connection);
        if (Flag == SocketConfig.SOCKET_SERVER_FLAG) {
            intent = new Intent(GameTransferActivity.this, SocketServerService.class);
        } else if (Flag == SocketConfig.SOCKET_CLIENT_FLAG) {
            intent = new Intent(GameTransferActivity.this, SocketClientService.class);
        }
        stopService(intent);
    }

    ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            if (iBinder instanceof SocketClientService.SocketBinder) {
                mSocket = ((SocketClientService.SocketBinder) iBinder).getSocket();
            } else if (iBinder instanceof SocketServerService.SocketBinder) {
                mSocket = ((SocketServerService.SocketBinder) iBinder).getSocket();
            }
            initServerAndClient();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        }
    };

    private void initServerAndClient() {
        if (mSocket == null) {
            return;
        }
        if (Flag == SocketConfig.SOCKET_SERVER_FLAG) {
            socketService = new SocketService(mContext, mSocket);
        } else if (Flag == SocketConfig.SOCKET_CLIENT_FLAG) {
            client = new ClientService(mContext, mSocket);
        }
        lastReceiverTime = System.currentTimeMillis();
        listenerSocketStatus();
    }

    //监听Sokcet 是否断开连接
    private void listenerSocketStatus() {
        mRunable = new SocketStatusRunable();
        mFuture = mExecutor.submit(mRunable);
    }

    //停止监听socket 连接状态
    private void stopListenerSocketStatus() {
        if (mRunable != null && mFuture != null) {
            mRunable.setMonitor(false);
            mFuture.cancel(true);
        }
    }

    //监听热点连接的客户端数量
    private void listApClients() {
        apClientRunable = new ScanApClientThread(mContext, true, 2000);
        apClientFuture = mExecutor.submit(apClientRunable);
    }


    //停止监听热点连接的数量
    void stopListenerApClients() {
        if (apClientRunable != null && apClientFuture != null) {
            if (!apClientFuture.isCancelled()) {
                apClientRunable.setMonitor(false);
                apClientFuture.cancel(true);
            }
        }
    }

    @OnClick({R.id.game_transfer_bottom_navigation_left_txt, R.id.game_transfer_bottom_navigation_right_txt
            , R.id.game_transfer_ok_btn, R.id.game_transfer_list_hint_close_img
            , R.id.game_transfer_list_choose_all_txt, R.id.game_transfer_back_img})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.game_transfer_bottom_navigation_left_txt:
                nagivationBarTextSelectedStatusChange(LEFT_BAR);
                break;
            case R.id.game_transfer_bottom_navigation_right_txt:
                nagivationBarTextSelectedStatusChange(RIGHT_BAR);
                break;
            case R.id.game_transfer_ok_btn:
                LogUtils.e("onClick: +时候可用" + tansfer_ok_btn.isEnabled());
                if (!sending) {
                    if (Flag == 1 && client != null) {
                        client.stopMonitor();
                    }
                    sending = true;
                    tansfer_ok_btn.setEnabled(false);
//                    updateGameFileStatu2Waiting();
                } else {
                    showLoading("请等待当前传输完成");
                }
                break;
            case R.id.game_transfer_list_hint_close_img:
//                prefDef.edit().showHistroyHint().put(false).apply();
                histroy_hint_rl.setVisibility(View.GONE);
                break;
            case R.id.game_transfer_list_choose_all_txt:
                if (!sending) {
//                    is_select_all = !is_select_all;
//                    select_all_txt.setSelected(is_select_all);
//                    updateGameListCheckStatus(is_select_all);
                }
                break;
            case R.id.game_transfer_back_img:
                showExitDialog();
                break;
            default:
                break;
        }
    }

    private void showExitDialog() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //此时已在主线程中，可以更新UI了
                showDialog();
            }
        });
    }

    private void showDialog() {
        mDialog = new MyDialog(this, R.style.MyDialog);
        mDialog.setContentView(R.layout.bind_dialog);

        Button dialog_button_cancel = (Button) mDialog.findViewById(R.id.dialog_button_cancel);
        Button dialog_button_ok = (Button) mDialog.findViewById(R.id.dialog_button_ok);
        TextView tip_title = (TextView) mDialog.findViewById(R.id.tip_title);
        TextView dialog_content = (TextView) mDialog.findViewById(R.id.dialog_content);
        TextView dialog_desci = (TextView) mDialog.findViewById(R.id.dialog_desci);

        tip_title.setText("提示");
        dialog_content.setText("退出会中断连接及正在进行的传输，确认退出吗？");
//        dialog_desci.setText("*绑定成功后将发送账号到你的手机");
        dialog_desci.setVisibility(View.GONE);
        dialog_button_cancel.setText("确认");
        dialog_button_ok.setText("取消");

        dialog_button_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialogDismiss();
                finish();
            }
        });
        dialog_button_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialogDismiss();
            }
        });
        if (null != mDialog) {
            if (mDialog.isShowing()) return;
            mDialog.show();
        }
    }

    private void dialogDismiss() {
        if (null != mDialog && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    class SocketStatusRunable implements Runnable {
        volatile boolean monitor = true;

        @Override
        public void run() {
            while (monitor) {
                try {
                    Thread.sleep(1000);
                    long interval_time = System.currentTimeMillis() - lastReceiverTime;
                    LogUtils.e("onTick: 间隔" + interval_time);
                    if (interval_time > SocketConfig.HEART_BEAT_TIME_OUT) {
                        LogUtils.e("onTick: 断开连接");
                        monitor = false;
                        GameTransferActivity.this.finish();
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    e.printStackTrace();
                }
            }
        }

        public void setMonitor(boolean monitor) {
            this.monitor = monitor;
        }
    }

    //导航text状态改变
    private void nagivationBarTextSelectedStatusChange(int which) {
        if (which == LEFT_BAR) {
            if (!left_nagivation_bar_txt.isTextSelectable()) {
                left_nagivation_bar_txt.setSelected(true);
                right_nagivation_bar_txt.setSelected(false);
                game_transfer_list.setVisibility(View.VISIBLE);
                game_transfer_historyList.setVisibility(View.GONE);
                tansfer_ok_btn.setVisibility(View.VISIBLE);
                select_all_txt.setVisibility(View.VISIBLE);
                select_num_txt.setVisibility(View.VISIBLE);
                histroy_hint_rl.setVisibility(View.GONE);
            }
        } else if (which == RIGHT_BAR) {
            if (!right_nagivation_bar_txt.isTextSelectable()) {
                right_nagivation_bar_txt.setSelected(true);
                left_nagivation_bar_txt.setSelected(false);
                game_transfer_list.setVisibility(View.GONE);
                game_transfer_historyList.setVisibility(View.VISIBLE);
                tansfer_ok_btn.setVisibility(View.GONE);
                select_all_txt.setVisibility(View.GONE);
                select_num_txt.setVisibility(View.GONE);
//                if (prefDef.showHistroyHint().get()) {
                    histroy_hint_rl.setVisibility(View.VISIBLE);
//                }
            }
        }
    }

    //监听热点状态
    private void registApWifiStatus() {
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.wifi.WIFI_AP_STATE_CHANGED");
        filter.addAction("android.net.wifi.WIFI_HOTSPOT_CLIENTS_CHANGED");
        apWifiConnectedReceiver = new ApWifiConnectedReceiver();
        registerReceiver(apWifiConnectedReceiver, filter);
    }

    //监听wifi 连接状态
    private void registWifiConnected() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        //这个监听网络连接的设置，包括wifi和移动数据的打开和关闭。.
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        netWorkConnectedReceiver = new NetWorkConnectedReceiver();
        registerReceiver(netWorkConnectedReceiver, filter);
    }

    private void unRegistReceiver() {
        if (netWorkConnectedReceiver != null) {
            unregisterReceiver(netWorkConnectedReceiver);
        }

        if (apWifiConnectedReceiver != null) {
            unregisterReceiver(apWifiConnectedReceiver);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (socketService != null) {
            socketService.release();
        }
        if (client != null) {
            client.release();
        }
        stopService();
        scManager.clearAllCommend();
        EventBus.getDefault().unregister(this);
        if (Flag == SocketConfig.SOCKET_SERVER_FLAG) {
            //关闭wifi 热点
            ApWifiUtil.getInstance(mContext).closeWifiAp();
            //打开wifi
            WifiUtils.getInstance(mContext).openWifi(mContext);
        }

        stopListenerSocketStatus();
        stopListenerApClients();
        unRegistReceiver();
        if (wakeLock != null) {
            wakeLock.release();
        }
        if (mExecutor != null && !mExecutor.isShutdown()) {
            mExecutor.shutdownNow();
        }

        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
            mDialog = null;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            showExitDialog();
        }
        return false;
    }
}
